package servlet;

import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import Dao.SalesRecordDao;
import Dao.ScenicSpotDao;
import Dao.UserInfoDao;
import entity.SalesRecord;
import entity.ScenicSpot;
import entity.UserInfo;

/**
 * Servlet implementation class scenicspotservlet
 */
@WebServlet("/scenicspotservlet")
public class scenicspotservlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public scenicspotservlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应内容类型
        response.setContentType("text/html;charset=UTF-8");

        try {
            // 从会话中获取当前用户信息
            HttpSession session = request.getSession();
            UserInfo userInfo = (UserInfo) session.getAttribute("userInfo");

            if (userInfo == null) {
                // 如果用户未登录，重定向到登录页面
                response.getWriter().write("<script>alert('请先登录！'); window.location.href='login.jsp';</script>");
                return;
            }

            // 获取当前用户的 userID
            int userID = userInfo.getUserID();

            // 获取请求参数
            String spotIDStr = request.getParameter("spotID");
            String quantityStr = request.getParameter("quantity");

            // 检查 spotID 和 quantity 是否为空
            if (spotIDStr == null || quantityStr == null || spotIDStr.isEmpty() || quantityStr.isEmpty()) {
                response.getWriter().write("<script>alert('参数错误，请检查输入！'); window.location.href='ticketpurchase.jsp';</script>");
                return;
            }

            int spotID = Integer.parseInt(spotIDStr);
            int quantity = Integer.parseInt(quantityStr);

            // 获取当前时间
            Date saleTime = new Date(System.currentTimeMillis());

            // 从数据库中获取景点信息
            ScenicSpotDao scenicSpotDao = new ScenicSpotDao();
            ScenicSpot spot = scenicSpotDao.getScenicSpotByID(spotID);

            if (spot!= null) {
                // 检查剩余票数是否足够
                if (spot.getRemainingTickets() >= quantity) {
                    // 根据会员类型获取折扣率并计算打折后的消费金额
                    BigDecimal discountRate =UserInfoDao.getUserDiscountRate(userID);
                    BigDecimal ticketPrice = spot.getTicketPrice();
                    BigDecimal consumptionAmount = ticketPrice.multiply(new BigDecimal(quantity)).multiply(discountRate);

                    // 创建销售记录对象
                    SalesRecord salesRecord = new SalesRecord();
                    salesRecord.setUserID(userID);
                    salesRecord.setSpotID(spotID);
                    salesRecord.setTicketQuantity(quantity);
                    salesRecord.setConsumptionAmount(consumptionAmount);
                    salesRecord.setSaleTime(saleTime);

                    // 保存销售记录到数据库
                    SalesRecordDao salesRecordDao = new SalesRecordDao();
                    boolean isSaved = salesRecordDao.saveSalesRecordAndUpdateUserAmount(salesRecord);

                    if (isSaved) {
                        // 更新景点剩余票数
                        int remainingTickets = spot.getRemainingTickets() - quantity;
                        spot.setRemainingTickets(remainingTickets);
                        scenicSpotDao.updateScenicSpot(spot);

                        UserInfo updatedUserInfo = UserInfoDao.findUserByUserID(userID); // 这里调用类似上述查找用户的方法获取最新信息
                        HttpSession session1 = request.getSession();
                        session1.setAttribute("userInfo", updatedUserInfo);
                        response.getWriter().write("<script>alert('购票成功！消费金额：" + consumptionAmount + "元'); setTimeout(function() { window.location.href='ticketpurchase.jsp'; }, 500);</script>");


                    } else {
                        response.getWriter().write("<script>alert('购票失败，请重试！'); window.location.href='ticketpurchase.jsp';</script>");
                    }
                } else {
                    response.getWriter().write("<script>alert('剩余票数不足，无法购票！'); window.location.href='ticketpurchase.jsp';</script>");
                }
            } else {
                response.getWriter().write("<script>alert('景点信息不存在！'); window.location.href='ticketpurchase.jsp';</script>");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            response.getWriter().write("<script>alert('数据库操作失败，请稍后重试！'); window.location.href='ticketpurchase.jsp';</script>");
        } catch (NumberFormatException e) {
            e.printStackTrace();
            response.getWriter().write("<script>alert('参数错误，请检查输入！'); window.location.href='ticketpurchase.jsp';</script>");
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("<script>alert('系统错误，请联系管理员！'); window.location.href='ticketpurchase.jsp';</script>");
        }
    }
    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
